// pages/rating.js
// pages/rating/index.js
const app = getApp()

Page({
  data: {
    productId: '',           // 商品ID
    productInfo: {},         // 商品信息
    totalScore: 0,           // 商品总分
    appearanceScore: 0,      // 外观评分
    performanceScore: 0,     // 性能评分
    priceScore: 0,           // 价格评分
    serviceScore: 0,         // 售后评分
    content: '',             // 评价内容
    isSubmitting: false,     // 是否正在提交
    hasRating: false         // 是否已有评价
  },

  onLoad: function(options) {
    const productId = options.id || getApp().globalData.currentProductId || '';
    this.setData({
      productId: options.id || ''
    });
    
    // 检查是否已有评价
    this.checkUserRating(productId);
  },

  // 检查用户是否已评价
  checkUserRating: function(productId) {
    // 这里替换为你的API调用
    app.api.goodsJudgeDetail(productId).then(res => {
      wx.hideLoading();
      if (res.data) {
        const rating = res.data;
        this.setData({
          totalScore: Number(rating.totalScore) || 0,
          appearanceScore: Number(rating.appearanceScore) || 0, // 如返回3
          performanceScore: Number(rating.performanceScore) || 0,
          priceScore: Number(rating.priceScore) || 0,
          serviceScore: Number(rating.serviceScore) || 0,
          content: rating.content || '',
          hasRating: true
        });
      } else {
        // 没有评价记录，重置为初始状态
        this.setData({
          totalScore: 0,
          appearanceScore: 0,
          performanceScore: 0,
          priceScore: 0,
          serviceScore: 0,
          content: '',
          hasRating: false
        });
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: '加载评价失败',
        icon: 'none'
      });
      console.error('加载评价失败:', err);
    });
  },
  
  // 评分商品总分
  rateTotal: function(e) {
    this.setData({
      totalScore: e.currentTarget.dataset.score
    });
  },

  // 评分外观
  rateAppearance: function(e) {
    this.setData({
      appearanceScore: e.currentTarget.dataset.score
    });
    this.calculateTotalScore();
  },

  // 评分性能
  ratePerformance: function(e) {
    this.setData({
      performanceScore: e.currentTarget.dataset.score
    });
    this.calculateTotalScore();
  },

  // 评分价格
  ratePrice: function(e) {
    this.setData({
      priceScore: e.currentTarget.dataset.score
    });
    this.calculateTotalScore();
  },

  // 评分售后
  rateService: function(e) {
    this.setData({
      serviceScore: e.currentTarget.dataset.score
    });
    this.calculateTotalScore();
  },

  // 计算总分
  calculateTotalScore: function() {
    const scores = [
      this.data.appearanceScore,
      this.data.performanceScore,
      this.data.priceScore,
      this.data.serviceScore
    ].filter(score => score > 0);
    
    if (scores.length > 0) {
      const total = scores.reduce((a, b) => a + b, 0) / scores.length;
      this.setData({
        totalScore: parseFloat(total.toFixed(1))
      });
    }
  },

  // 更新评价内容
  updateContent: function(e) {
    this.setData({
      content: e.detail.value
    });
  },

  // 提交评价
  submitRating: function() {
    if (this.data.isSubmitting) return;
    
    // 验证评分
    if (this.data.totalScore === 0) {
      wx.showToast({
        title: '请为商品评分',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ isSubmitting: true });
  
    // 提交评分接口
    app.api.goodsJudge(this.data).then(res => {
      if (res.code === 0) { // 假设接口返回 code=0 表示成功
        wx.showToast({
          title: '评价成功',
          icon: 'success',
          duration: 1500
        });
        
        // 1.5秒后重新加载评价数据
        setTimeout(() => {
          this.checkUserRating(this.data.productId);
          this.setData({ isSubmitting: false });
        }, 1500);
      } else {
        wx.showToast({
          title: res.msg || '评价失败',
          icon: 'none'
        });
        this.setData({ isSubmitting: false });
      }
    }).catch(err => {
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
      this.setData({ isSubmitting: false });
      console.error('提交评价失败:', err);
    });
  }
});